<template>
  <div class="stroke-events-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>卒中事件管理</span>
          <el-button type="primary" @click="showAddEventDialog">添加事件</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="患者姓名">
            <el-input 
              v-model="searchForm.patient_name" 
              placeholder="请输入患者姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="事件类型">
            <el-select 
              v-model="searchForm.event_type" 
              placeholder="请选择事件类型"
              clearable
            >
              <el-option label="缺血性卒中" value="缺血性卒中"></el-option>
              <el-option label="出血性卒中" value="出血性卒中"></el-option>
              <el-option label="短暂性脑缺血发作" value="短暂性脑缺血发作"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发病时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="paginatedEvents" 
        style="width: 100%"
        border
      >
        <el-table-column prop="event_id" label="事件ID" width="100" />
        <el-table-column 
            prop="患者ID" 
            label="患者信息" 
            width="200" 
            :formatter="formatPatientInfo"
          />
        <el-table-column prop="onset_time" label="发病时间" width="180" />
        <el-table-column prop="admission_time" label="入院时间" width="180" />
        <el-table-column prop="affected_area" label="发病部位" width="120" />
        <el-table-column prop="severity" label="严重程度" width="100" />
        <el-table-column prop="event_type" label="事件类型" width="120" />
        <el-table-column prop="creation_time" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewEventDetail(row.event_id)">详情</el-button>
            <el-button type="warning" size="small" @click="editEvent(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteEvent(row.event_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredEvents.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑卒中事件对话框 -->
    <el-dialog
      v-model="eventDialogVisible"
      :title="dialogType === 'add' ? '添加卒中事件' : '编辑卒中事件'"
      width="800px"
    >
      <el-form 
        :model="eventForm" 
        ref="eventFormRef" 
        label-width="120px"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者ID" prop="patient_id" v-if="dialogType === 'edit'">
              <el-input v-model="eventForm.patient_id" disabled />
            </el-form-item>
            <el-form-item label="选择患者" prop="patient_id" v-else>
              <el-select v-model="eventForm.patient_id" placeholder="请选择患者" filterable>
                <el-option 
              v-for="p in patients" 
              :key="p.patient_id" 
              :label="`${p.patient_name} (${p.id_card || p.身份证号})`" 
              :value="p.patient_id"
            ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发病时间" prop="onset_time">
              <el-date-picker
                v-model="eventForm.onset_time"
                type="datetime"
                placeholder="选择发病时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入院时间" prop="admission_time">
              <el-date-picker
                v-model="eventForm.admission_time"
                type="datetime"
                placeholder="选择入院时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出院时间" prop="discharge_time">
              <el-date-picker
                v-model="eventForm.discharge_time"
                type="datetime"
                placeholder="选择出院时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发病部位" prop="affected_area">
              <el-select v-model="eventForm.affected_area" placeholder="请选择发病部位">
                <el-option label="前循环" value="前循环"></el-option>
                <el-option label="后循环" value="后循环"></el-option>
                <el-option label="多发" value="多发"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="严重程度" prop="severity">
              <el-select v-model="eventForm.severity" placeholder="请选择严重程度">
                <el-option label="轻度" value="轻度"></el-option>
                <el-option label="中度" value="中度"></el-option>
                <el-option label="重度" value="重度"></el-option>
                <el-option label="极重度" value="极重度"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件类型" prop="event_type">
              <el-select v-model="eventForm.event_type" placeholder="请选择事件类型">
                <el-option label="缺血性卒中" value="缺血性卒中"></el-option>
                <el-option label="出血性卒中" value="出血性卒中"></el-option>
                <el-option label="短暂性脑缺血发作" value="短暂性脑缺血发作"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否复发" prop="is_recurrence">
              <el-select v-model="eventForm.is_recurrence" placeholder="请选择是否复发">
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="临床表现" prop="clinical_manifestation">
              <el-input 
                v-model="eventForm.clinical_manifestation" 
                placeholder="请输入临床表现"
                type="textarea"
                rows="3"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="影像学检查结果" prop="imaging_results">
              <el-input 
                v-model="eventForm.imaging_results" 
                placeholder="请输入影像学检查结果"
                type="textarea"
                rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="eventDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEventForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { strokeEventAPI, patientAPI } from '../api'

const router = useRouter()
const route = useRoute()

// 状态数据
const loading = ref(false)
const events = ref([])
const patients = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchForm = ref({
  patient_name: '',
  event_type: ''
})
const dateRange = ref([])

// 对话框相关
const eventDialogVisible = ref(false)
const dialogType = ref('add')
const eventFormRef = ref()
const eventForm = ref({
  event_id: '',
  患者ID: '',
  onset_time: '',
  admission_time: '',
  discharge_time: '',
  affected_area: '',
  severity: '',
  event_type: '',
  is_recurrence: '',
  clinical_manifestation: '',
  imaging_results: ''
})

// 表单验证规则
const formRules = {
  patient_id: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  onset_time: [
    { required: true, message: '请选择发病时间', trigger: 'change' }
  ],
  admission_time: [
    { required: true, message: '请选择入院时间', trigger: 'change' }
  ],
  affected_area: [
    { required: true, message: '请选择发病部位', trigger: 'change' }
  ],
  severity: [
    { required: true, message: '请选择严重程度', trigger: 'change' }
  ],
  event_type: [
    { required: true, message: '请选择事件类型', trigger: 'change' }
  ],
  is_recurrence: [
    { required: true, message: '请选择是否复发', trigger: 'change' }
  ],
  clinical_manifestation: [
    { required: true, message: '请输入临床表现', trigger: 'blur' }
  ],
  imaging_results: [
    { required: true, message: '请输入影像学检查结果', trigger: 'blur' }
  ]
}

// 根据搜索条件过滤事件
const filteredEvents = computed(() => {
  let result = events.value
  
  // 根据患者姓名过滤
  if (searchForm.value.patient_name) {
    const name = searchForm.value.patient_name
    result = result.filter(event => {
      const patient = patients.value.find(p => p.patient_id === event.patient_id)
      return patient && patient.patient_name.includes(name)
    })
  }
  
  // 根据事件类型过滤
  if (searchForm.value.event_type) {
    result = result.filter(event => event.event_type === searchForm.value.event_type)
  }
  
  // 根据日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(event => {
      const eventDate = new Date(event.onset_time)
      return eventDate >= startDate && eventDate <= endDate
    })
  }
  
  return result
})

// 分页事件
const paginatedEvents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredEvents.value.slice(start, end)
})

// 获取数据
const getData = async () => {
  loading.value = true
  try {
    // 获取卒中事件列表
    const eventsData = await strokeEventAPI.getEvents()
    events.value = eventsData
    
    // 获取患者列表
  const patientsData = await patientAPI.getPatients()
  patients.value = patientsData
    
    // 检查是否有需要预设的患者ID（从URL参数）
    const presetPatientId = route.query.patientId
    if (presetPatientId) {
      showAddEventDialog(parseInt(presetPatientId))
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    patient_name: '',
    event_type: ''
  }
  dateRange.value = []
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 显示添加事件对话框
const showAddEventDialog = (presetPatientId = null) => {
  dialogType.value = 'add'
  eventForm.value = {
    event_id: '',
    patient_id: presetPatientId || '',
    onset_time: '',
    admission_time: '',
    discharge_time: '',
    affected_area: '',
    severity: '',
    event_type: '',
    is_recurrence: '',
    clinical_manifestation: '',
    imaging_results: ''
  }
  eventDialogVisible.value = true
}

// 编辑事件
const editEvent = (row) => {
  dialogType.value = 'edit'
  eventForm.value = { ...row }
  eventDialogVisible.value = true
}

// 提交表单
const submitEventForm = async () => {
  try {
    await eventFormRef.value.validate()
    
    if (dialogType.value === 'add') {
      // 生成事件ID
      const newEvent = {
        ...eventForm.value,
        event_id: Date.now(), // 简单生成ID
        creation_time: new Date().toISOString()
      }
      
      await strokeEventAPI.addEvent(newEvent)
      ElMessage.success('卒中事件添加成功')
    } else {
      const updatedEvent = {
        ...eventForm.value,
        update_time: new Date().toISOString()
      }
      await strokeEventAPI.updateEvent(updatedEvent)
      ElMessage.success('卒中事件更新成功')
    }
    
    eventDialogVisible.value = false
    getData() // 重新获取数据
  } catch (error) {
    if (error !== false) { // 非表单验证错误
      ElMessage.error('操作失败，请重试')
      console.error('操作失败:', error)
    }
  }
}

// 删除事件
const deleteEvent = async (eventId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该卒中事件记录吗？此操作不可撤销！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await strokeEventAPI.deleteEvent(eventId)
    ElMessage.success('卒中事件记录已删除')
    getData() // 重新获取数据
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

// 查看事件详情
const viewEventDetail = (eventId) => {
  router.push(`/stroke-events/${eventId}`)
}

// 格式化患者信息
const formatPatientInfo = (row) => {
  // 使用标准化后的字段名patient_id进行查找
  const patient = patients.value.find(p => p.patient_id === row.patient_id)
  return patient ? `${patient.patient_name} (ID: ${patient.patient_id})` : '未知患者'
}

// 组件挂载时获取数据
onMounted(() => {
  getData()
})
</script>

<style scoped>
.stroke-events-container {
  padding: 20px;
  background-color: #FFFFFF;
  min-height: 100vh;
}

.page-card {
  margin-bottom: 20px;
  background-color: #FFFFFF;
  border: 1px solid #e0e0e0;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保标题文字为黑色 */
.card-header span {
  color: #000000 !important;
}

.search-filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #FFFFFF;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  box-shadow: none;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格样式 */
:deep(.el-table) {
  --el-table-bg-color: #FFFFFF;
  --el-table-header-bg-color: #f5f5f5;
  --el-table-border-color: #e0e0e0;
  --el-table-text-color: #000000;
}

:deep(.el-table thead) {
  --el-table-header-cell-text-color: #000000;
}

:deep(.el-table tbody) {
  --el-table-row-hover-bg-color: #f5f5f5;
  --el-table-row-current-bg-color: #e6f7ff;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  color: #000000;
}

:deep(.el-input__wrapper) {
  background-color: #FFFFFF;
  border-color: #dcdfe6;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__inner) {
  color: #000000;
}

:deep(.el-input__placeholder) {
  color: #909399;
}

:deep(.el-select__wrapper) {
  background-color: #FFFFFF;
  border-color: #dcdfe6;
}

:deep(.el-select__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
}

:deep(.el-select__inner) {
  color: #000000;
}

:deep(.el-select__placeholder) {
  color: #909399;
}

/* 对话框样式 */
:deep(.el-dialog__title) {
  color: #000000;
}

:deep(.el-dialog__body) {
  background-color: #FFFFFF;
  color: #000000;
}

:deep(.el-dialog__footer) {
  background-color: #FFFFFF;
  border-top: 1px solid #e0e0e0;
}

:deep(.el-date-editor .el-input__wrapper) {
  background-color: #FFFFFF;
  border-color: #dcdfe6;
}

:deep(.el-date-editor .el-input__inner) {
  color: #000000;
}

/* 分页组件样式 */
:deep(.el-pagination__total) {
  color: #000000;
}

:deep(.el-pagination__sizes .el-input__wrapper) {
  background-color: #FFFFFF;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
}

@media (max-width: 768px) {
  .stroke-events-container {
    padding: 10px;
  }
  
  .pagination-container {
    justify-content: center;
  }
  
  .el-button {
    font-size: 12px;
    padding: 6px 12px;
  }
}
</style>